package com.ldatum.crm.common;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class VerifyCode extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("image/jpeg");
		//创建内存映像对象
		BufferedImage image = 
			new BufferedImage(60,20,
					BufferedImage.TYPE_INT_RGB);
		//获得画笔
		Graphics g = image.getGraphics();
		//填充背景
		Random r = new Random();
		g.setColor(new Color(255,
				255,255));
		g.fillRect(0, 0, 60, 20);
		//绘画
		String number = getCodeByDigits();
		//将number绑订到session
		HttpSession session = request.getSession();
		session.setAttribute("number", number);
		g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
		g.setFont(new Font("宋体",Font.BOLD,16));
		g.drawString(number, 5, 15);
		//加一些干扰线
		for(int i=0;i<2;i++){
			g.drawLine(r.nextInt(60), r.nextInt(20), 
					r.nextInt(60), r.nextInt(20));
		}
		//压缩图片，输出
		OutputStream ops = response.getOutputStream();
		javax.imageio.ImageIO.write(
				image, "jpg", ops);
		
	}
	
	@SuppressWarnings("unused")
	private String getCheckcode(){
		String code = "";
		char[] codes = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
				'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W','X','Y','Z'};
		Random r = new Random();
		for(int i=0;i<5;i++){
			code +=codes[r.nextInt(codes.length)];
		}
		return code; 
	}
	
	private String getCodeByDigits(){
		String code = "";
		char[] codes = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
		Random r = new Random();
		for(int i=0;i<5;i++){
			code +=codes[r.nextInt(codes.length)];
		}
		return code;
	}

}
